﻿using AutoMapper;
using FinancialManagement.Application.Command.ReceivableCommand;
using FinancialManagement.Domain.Dto;
using FinancialManagement.Domain.Dto.SaleContract;
using FinancialManagement.Domain.Model;
using FinancialManagement.Dtos;
using FinancialManagement.Infrstructre.Interface;
using MediatR;
using MySqlX.XDevAPI.Common;
using SqlSugar;

namespace FinancialManagement.Application.CommandHandler.ReceivableCommandHandler
{
    /// <summary>
    /// 应收管理
    /// </summary>
    public class ListReceivableCommandHandler : IRequestHandler<ListReceivableCommand, PageDto<ListReceivableDto>>
    {
        
        ISqlSugarClient db;

        public ListReceivableCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }


        public async Task<PageDto<ListReceivableDto>> Handle(ListReceivableCommand request, CancellationToken cancellationToken)
        {
            var list = db.Queryable<Domain.Model.SaleContractProduct>()
                 .LeftJoin<SaleContract>((scp, sc) => scp.SCcontractNumber == sc.SCcontractNumber)
                 .Where(scp => scp.IsDel == false)
                 .GroupBy((scp, sc) => new { scp.SCcontractNumber, sc.ClientName,sc.ContractTopic, sc.PreferentialPrice })
                 .Select((scp, sc) => new ListReceivableDto
                 {
                     SCcontractNumber=scp.SCcontractNumber,
                     ClientName = sc.ClientName,
                     ContractTopic = sc.ContractTopic,
                     PreferentialPrice = sc.PreferentialPrice,
                     PlanAmount = SqlFunc.AggregateSum(sc.PreferentialPrice),
                 }).ToList();
            if (!string.IsNullOrEmpty(request.AClientName))
            {
                list = list.Where(x => x.AClientName.Contains(request.AClientName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ContractTopic))
            {
                list = list.Where(x => x.ContractTopic.Contains(request.ContractTopic)).ToList();
            }


            PageDto<ListReceivableDto> page = new PageDto<ListReceivableDto>();
            page.lcount = list.Count();
            page.pcount = (int)Math.Ceiling(page.lcount * 1.0 / request.Psize);
            page.list = list.Skip((request.Pindex - 1) * request.Psize).Take(request.Psize).ToList();
            return page;


        }
    }
}
